package graduation.project.store;

import graduation.project.body.OriginExpression;
import graduation.project.exception.NonExpressionException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileOriginExpression implements IOriginExpression {

	public OriginExpression getOriginExpression(String originExID) {
		OriginExpression originEx = null;
		try{
			File fileOriginEx = new File("D:\\data\\" + originExID + "\\originExpression\\" + originExID);
			BufferedReader in = new BufferedReader(new FileReader(fileOriginEx));
			String originID = in.readLine();
			String originExp = in.readLine();
			
			originEx = new OriginExpression(originID, originExp);
			in.close();
		}catch (FileNotFoundException e) {
			System.out.println("The file does not exist");
			e.printStackTrace();
		}catch(IOException e){
			System.out.println("Occurring error when read file");
			e.printStackTrace();
		}catch (NonExpressionException e){
			System.out.println("invalid expression");
			e.printStackTrace();
		}
		
		return originEx;
	}

	public int insertOriginExpression(OriginExpression originEx) {
		int result = 0;
		if(originEx == null)
			return 0;
		try{
			File dir = new File("D:\\data\\" + originEx.getOriginExID() + "\\originExpression");
			dir.mkdirs();
			File fileOriginEx = new File("D:\\data\\" + originEx.getOriginExID() + "\\originExpression\\" + originEx.getOriginExID());
			if(!(fileOriginEx.createNewFile())){
				System.out.println("the file has existed.");
				return 0;
			}
			
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileOriginEx)));
			out.println(originEx.getOriginExID());
			out.println(originEx.getExpression());
			out.println(originEx.getDNF());
			out.println(originEx.getIDNF());
			
			result = 1;
			out.close();
		}catch(IOException e){
			System.out.println("Occurring errors when write the file.");
			e.printStackTrace();
		}
		return result;
	}

	public int modifyOriginExpression(OriginExpression originEx) {
		// TODO Auto-generated method stub
		return 0;
	}

}
